// Socket封装
import defines from 'defines'
import EventListener from '../communal/eventListener';

const socketControlle = ()=>{
    let that = {};
    // 当前类的Socket
    let _socket = undefined;
    let _callBackIndex = 1;
    let _callBackMap = {};
    let _event = EventListener({});

    // 初始化网络环境
    that.init = ()=>{
        _socket = io('http://192.168.111.134:3001');
        _socket.on('notify', (data)=>{
            let callBackIndex = data.callBackIndex;
            let msg = data.msg;
            _event.fire(msg, data.data);
            if (callBackIndex) {
                let cb = _callBackMap[callBackIndex];
                if (cb){
                    cc.log('回调 = ' + JSON.stringify(data.data));
                    if (data.data.err) {
                        cb(data.data.err);
                    } else {
                        cb(null, data.data);
                    }
                }
            }
        });
    };

    // 网络发送数据
    const notify = (msg, data)=>{
        _socket.emit('notify', {msg: msg, callBackIndex: _callBackIndex, data: data});
        _callBackIndex++;
    };

    // 网络发送数据
    const request = (msg, data, cb)=>{
        _callBackMap[_callBackIndex] = cb;
        notify(msg, data);
    };

    // 发送登录数据
    // 账号，密码，唯一ID，名字，头像，回调
    that.login = (an, pw, unique, name, url, cb)=>{
        request('login', {account: an, password: pw, uniqueID: unique, nickName: name, avatarUrl: url}, cb);
    };

    // 发送登录数据
    // 账号，密码，唯一ID，名字，头像，回调
    that.onLogin = (cb)=>{
        _event.on('login', cb);
    };

    // 发送创建角色进入游戏
    that.creatorPlayer = (id, num, name, url, cb)=>{
        request('createrplayer', {gameid: id, playernum: num, nickName: name, avatarUrl: url}, cb);
    };

  
    return that;
};

export default socketControlle;